const express = require('express');
const http = require('http');
const express = require('express');
const WebSocket = require('ws');
const path = require('path');
const { User, Document } = require('./db');
const createApiRouter = require('./api');

// 创建Express应用
const app = express();
const PORT = 3000;  // 改回3000端口

// CORS middleware
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  if (req.method === 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
});

// 中间件
app.use(express.json());
app.use(express.static(path.join(__dirname, '../dist')));

// 使用API路由
const api = createApiRouter(express);
app.use('/api', api);

// 创建HTTP服务器
const server = http.createServer(app);

// 创建WebSocket服务器
const wss = new WebSocket.Server({ server });

// 存储所有连接的客户端
// 结构: Map<WebSocket, { id: string, name: string, color: string, documentId: number|null }>
const clients = new Map();

wss.on('connection', (ws, req) => {
  console.log('New client connected');
  // 初始化客户端信息
  clients.set(ws, { id: null, name: null, color: null, documentId: null });
  
  // 发送欢迎消息
  ws.send(JSON.stringify({ type: 'connected', message: 'Connected to collaboration server' }));
  
  // 监听客户端消息
  ws.on('message', (message) => {
    try {
      const data = JSON.parse(message);
      console.log('Received message:', data);
      
      // 处理不同类型的用户消息
      switch (data.type) {
        case 'user-join':
          // 更新客户端信息
          clients.set(ws, data.user);
          console.log('Updated client info:', data.user);
          // 广播新用户加入消息（只广播给同一文档的用户）
          let broadcastCount = 0;
          clients.forEach((userInfo, client) => {
            if (client !== ws && client.readyState === WebSocket.OPEN && 
                userInfo.documentId === data.user.documentId) {
              client.send(JSON.stringify({
                type: 'user-join',
                user: data.user
              }));
              broadcastCount++;
            }
          });
          console.log(`Broadcasted user-join to ${broadcastCount} clients`);
          break;
          
        case 'user-update':
          // 更新用户信息（如光标位置）
          const userInfo = clients.get(ws);
          if (userInfo) {
            // 更新客户端信息
            const updatedUserInfo = { ...userInfo, ...data.user };
            clients.set(ws, updatedUserInfo);
            // 广播用户更新消息（只广播给同一文档的用户）
            let updateBroadcastCount = 0;
            clients.forEach((userInfo, client) => {
              if (client !== ws && client.readyState === WebSocket.OPEN && 
                  userInfo.documentId === data.user.documentId) {
                client.send(JSON.stringify({
                  type: 'user-update',
                  user: updatedUserInfo
                }));
                updateBroadcastCount++;
              }
            });
            console.log(`Broadcasted user-update to ${updateBroadcastCount} clients`);
          }
          break;
          
        case 'user-leave':
          // 广播用户离开消息（只广播给同一文档的用户）
          const leavingUser = clients.get(ws);
          if (leavingUser) {
            let leaveBroadcastCount = 0;
            clients.forEach((userInfo, client) => {
              if (client !== ws && client.readyState === WebSocket.OPEN && 
                  userInfo.documentId === leavingUser.documentId) {
                client.send(JSON.stringify({
                  type: 'user-leave',
                  user: leavingUser
                }));
                leaveBroadcastCount++;
              }
            });
            console.log(`Broadcasted user-leave to ${leaveBroadcastCount} clients`);
          }
          break;
          
        case 'document-update':
          // 处理文档更新消息
          // 广播文档更新消息给同一文档的其他客户端
          let docUpdateBroadcastCount = 0;
          clients.forEach((userInfo, client) => {
            if (client !== ws && client.readyState === WebSocket.OPEN && 
                userInfo.documentId === data.documentId) {
              client.send(JSON.stringify({
                type: 'document-update',
                content: data.content,
                documentId: data.documentId
              }));
              docUpdateBroadcastCount++;
            }
          });
          console.log(`Broadcasted document-update to ${docUpdateBroadcastCount} clients`);
          break;
          
        default:
          // 广播其他消息给所有其他客户端
          clients.forEach((userInfo, client) => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
              client.send(JSON.stringify(data));
            }
          });
      }
    } catch (error) {
      console.error('Error parsing message:', error);
    }
  });
  
  // 监听客户端断开连接
  ws.on('close', (code, reason) => {
    console.log('Client disconnected. Code:', code, 'Reason:', reason?.toString());
    const userInfo = clients.get(ws);
    console.log('Disconnected client info:', userInfo);
    if (userInfo) {
      // 广播用户离开消息（只广播给同一文档的用户）
      let leaveBroadcastCount = 0;
      clients.forEach((info, client) => {
        if (client !== ws && client.readyState === WebSocket.OPEN && 
            info.documentId === userInfo.documentId) {
          client.send(JSON.stringify({
            type: 'user-leave',
            user: userInfo
          }));
          leaveBroadcastCount++;
        }
      });
      console.log(`Broadcasted user-leave to ${leaveBroadcastCount} clients`);
    }
    clients.delete(ws);
    console.log('Client removed from clients map. Remaining clients:', clients.size);
  });
  
  // 监听错误
  ws.on('error', (error) => {
    console.error('WebSocket error:', error);
    console.error('Error stack:', error.stack);
    clients.delete(ws);
  });
});

// 启动服务器
server.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log(`WebSocket server running on ws://localhost:${PORT}`);
});